package com.ruoyi.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.appuser.domain.Appuser;
import com.ruoyi.appuser.service.IAppuserService;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.season.domain.PlaySeason;
import com.ruoyi.season.domain.PlaySeasonRecord;
import com.ruoyi.season.service.IPlaySeasonRecordService;
import com.ruoyi.season.service.IPlaySeasonService;
import com.ruoyi.util.DateUtils;
import com.ruoyi.util.WechatConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author mjl
 */
@RestController
@RequestMapping("/app-api/login")
@Api(value = "登录",tags = "移动端接口")
public class AppLoginController {

    @Resource
    private IAppuserService appuserService;
    @Resource
    private IPlaySeasonService playSeasonService;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private IPlaySeasonRecordService playSeasonRecordService;


    @PassToken
    @PostMapping("/wechatLogin")
    @ApiOperation(value = "小程序授权登录", notes = "code,nickname用户名,avatar")
    public R authLogin(String code,String nickname,String avatar){
        RestTemplate restTemplate = new RestTemplate();

        String access_token_url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid={appId}&secret={secret}&js_code={js_code}&grant_type=authorization_code";
        //设置请求参数
        Map<String, String> params = new HashMap<>(5);
        params.put("appId", WechatConstants.WECHAT_MP_APPID);
        params.put("secret", WechatConstants.WECHAT_MP_SECRET);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        /**通过 code 换取微信openid*/
        String json = restTemplate.getForObject(access_token_url, String.class, params);
        JSONObject accessToken = JSON.parseObject(json);
        System.out.println("========accessToken==============="+accessToken.toJSONString());

        String openid = accessToken.getString("openid");
        String unionid = accessToken.getString("unionid");
        String sessionKey = accessToken.getString("session_key");

        Appuser appuser = appuserService.getOne(new QueryWrapper<Appuser>().eq("open_id",openid));

        Map<String, Object> result = new HashMap<>(6);

        if (Objects.isNull(appuser) || StringUtils.isBlank(appuser.getId()) ) {

            Appuser insertUser = new Appuser();
            Date date = new Date();
            insertUser.setNickname(StringUtils.isEmpty(nickname) ? "微信用户" : nickname);
            insertUser.setAvatar(avatar);
            insertUser.setUnionId(unionid);
            insertUser.setOpenId(openid);
            insertUser.setCreateTime(date);
            insertUser.setUpdateTime(date);
            if (!appuserService.save(insertUser)) {
                return R.fail("注册失败");
            }

            PlaySeason playSeason = playSeasonService.getOne(new LambdaQueryWrapper<PlaySeason>()
                    .eq(PlaySeason :: getType,1).eq(PlaySeason :: getIsDeleted,0));
            if(Objects.nonNull(playSeason) && StringUtils.isNotBlank(playSeason.getId())){
                /**参加赛季记录*/
                PlaySeasonRecord playSeasonRecord = new PlaySeasonRecord();
                playSeasonRecord.setAppuserId(insertUser.getId());
                playSeasonRecord.setCreateTime(date);
                playSeasonRecord.setType(1);
                playSeasonRecord.setPlaySeasonId(playSeason.getId());
                playSeasonRecord.setStatus(2);
                if(!playSeasonRecordService.save(playSeasonRecord)){
                    return R.fail("赛季记录失败");
                }
                insertUser.setPlaySeasonRecordId(playSeasonRecord.getId());
                if (!appuserService.updateById(insertUser)) {
                    return R.fail("用户信息修改失败");
                }
            }
            String token = setAppUserInfo(insertUser);
            result.put("userInfo", insertUser);
            result.put("token", token);

        } else {
            String token = setAppUserInfo(appuser);
            result.put("userInfo", appuser);
            result.put("token", token);
        }
        result.put("sessionKey",sessionKey);

        return R.ok(result);
    }

    public String setAppUserInfo(Appuser appuser){
        String token = UUID.randomUUID().toString() + '-' + appuser.getId();
        /**有效期十二小时*/
        redisCache.setCacheObject(token, appuser, 12 * 60 * 60, TimeUnit.SECONDS);
        return token;
    }


    /**
     * 登录授权绑定手机号
     */
//    @PostMapping("/bindMobile")
//    @ApiOperation(value = "绑定手机号", notes = "code,id用户id")
    public R bindMobile(String id ,String code) {
        Appuser appuser = appuserService.getById(id);
        if (appuser == null) {
            return R.fail("用户不存在");
        }

        RestTemplate restTemplate = new RestTemplate ();
        /**获得token*/
        String accessTokenmap = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"
                , String.class, WechatConstants.WECHAT_MP_APPID, WechatConstants.WECHAT_MP_SECRET);
        System.out.println("================="+accessTokenmap);

        Map<String,String> map = JSON.parseObject(accessTokenmap, Map.class);
        String accessToken = map.get("access_token");
        Map<String, Object> result = new HashMap<>(3);
        result.put("code",code);
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("Accept","application/json");
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(result, httpHeaders);
        /**获取手机号信息*/
        String post = restTemplate.postForObject(url, httpEntity, String.class);
        Map<String,Object> map1 = JSON.parseObject(post, Map.class);
        String errcode = map1.get("errcode") + "";
        if (!StringUtils.isEmpty(errcode) && "0".equals(errcode)){
            String phoneInfo = map1.get("phone_info") + "";
            Map<String,String> map2 = JSON.parseObject(phoneInfo, Map.class);

            if (StringUtils.isEmpty(map2.get("purePhoneNumber"))) {
                return R.fail("手机号授权失败，请重试");
            }
            String purePhoneNumber = map2.get("purePhoneNumber");
            appuser.setMobile(purePhoneNumber);
            appuser.setUpdateTime(new Date());
            if (!appuserService.updateById(appuser)) {
                return R.fail("手机号绑定失败");
            }
            return R.ok();
        }else {
            return R.fail("获取手机号失败");
        }

    }

    /**测试接口*/
    @PassToken
    @PostMapping("/test1")
    @ApiOperation(value = "测试登录",notes = " ")
    public R test1() {
        HashMap<String,Object> result = new HashMap(4);
        Appuser appuser = appuserService.getById("123");

        String token = setAppUserInfo(appuser);
        result.put("userInfo", appuser);
        result.put("token", token);
        result.put("sessionKey","会话");
        return R.ok(result);
    }


}
